package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.product.dao.ProOutsourcingOrderDao;

import com.wing.product.model.entity.ProOutsourcingOrder;

import com.wing.product.model.entity.ProOutsourcingOrderProduct;
import com.wing.product.model.entity.ProOutsourcingOrderProductDetail;
import com.wing.product.model.request.ProOutsourcingOrderAddOrUpdateForm;
import com.wing.product.model.response.ProOutsourcingOrderProductDetailGroupVo;
import com.wing.product.model.response.ProOutsourcingOrderSearchVO;
import com.wing.res.model.response.ResWorkStationSearchVo;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 委外订单
 *
 * @author hz
 */
@Service
@Slf4j
public class ProOutsourcingOrderServiceImpl extends ServiceImpl<ProOutsourcingOrderDao, ProOutsourcingOrder> implements ProOutsourcingOrderService {

    @Resource
    DynamicService dynamicService;

    @Autowired
    private ProOutsourcingOrderProductService proOutsourcingOrderProductService;

    @Autowired
    private ProOutsourcingOrderProductDetailService proOutsourcingOrderProductDetailService;

    @Autowired
    private UserClient userClient;

    /**
     * 查询委外订单列表
     *
     * @param pg
     * @param paramMap
     * @return
     */
    @Override
    public IPage<ProOutsourcingOrder> pageList4app(Page<ProOutsourcingOrder> pg, Map<String, Object> paramMap) {
        List<ProOutsourcingOrder> vos = this.baseMapper.pageList4app(pg, paramMap);
        pg.setRecords(vos);
        return pg;
    }

    /**
     * 添加委外订单
     *
     * @param proOutsourcingOrderAddOrUpdateForm 订单入参
     * @return 是否添加成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ProOutsourcingOrderAddOrUpdateForm proOutsourcingOrderAddOrUpdateForm) {
        //1. 加入订单详情
        ProOutsourcingOrder proOutsourcingOrder = new ProOutsourcingOrder();
        BeanUtil.copyProperties(proOutsourcingOrderAddOrUpdateForm, proOutsourcingOrder);
        proOutsourcingOrder.setCreateTime(LocalDateTime.now());
        proOutsourcingOrder.setUpdateTime(LocalDateTime.now());
        proOutsourcingOrder.setCreator(JwtUtils.getLoginUserId());
        proOutsourcingOrder.setCreatorName(JwtUtils.getLoginUsername());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("code", "pro_outsourcing_order_product");
        String day = simpleDateFormat.format(new Date());
        proOutsourcingOrder.setNo(Integer.valueOf(code));
        proOutsourcingOrder.setCode(code);
        proOutsourcingOrder.setCode("WW" + day + code);
        boolean save = this.save(proOutsourcingOrder);
        //2. 加入订单的产品
        if (save) {
            List<ProOutsourcingOrderProduct> products = proOutsourcingOrderAddOrUpdateForm.getProductList();
            for (ProOutsourcingOrderProduct product : products) {
                product.setCreateTime(LocalDateTime.now());
                product.setUpdateTime(LocalDateTime.now());
                product.setCreator(JwtUtils.getLoginUserId());
                product.setCreatorName(JwtUtils.getLoginUsername());
                product.setOrderId(proOutsourcingOrder.getId());
                boolean info = this.proOutsourcingOrderProductService.save(product);
                if (info) {
                    List<ProOutsourcingOrderProductDetail> productDetails = product.getProductDetails();
                    if (CollectionUtil.isNotEmpty(productDetails)) {
                        for (ProOutsourcingOrderProductDetail productDetail : productDetails) {
                            productDetail.setCreateTime(LocalDateTime.now());
                            productDetail.setUpdateTime(LocalDateTime.now());
                            productDetail.setCreator(JwtUtils.getLoginUserId());
                            productDetail.setCreatorName(JwtUtils.getLoginUsername());
                            productDetail.setOutsourcingId(product.getId());
                        }
                        this.proOutsourcingOrderProductDetailService.saveBatch(productDetails);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 根据订单id查询委外的详情
     *
     * @param orderId 工单id
     * @return 详情
     */
    @Override
    public ProOutsourcingOrderSearchVO getDetailBy(Long orderId) {
        ProOutsourcingOrderSearchVO searchVO = new ProOutsourcingOrderSearchVO();
        //订单信息
        ProOutsourcingOrder byId = this.getById(orderId);
        BeanUtil.copyProperties(byId, searchVO);
        //查询订单下的产品
        QueryWrapper<ProOutsourcingOrderProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.orderByDesc("create_time");
        List<ProOutsourcingOrderProduct> list = this.proOutsourcingOrderProductService.list(queryWrapper);
        List<Long> ids = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (ProOutsourcingOrderProduct proOutsourcingOrderProduct : list) {
                ids.add(proOutsourcingOrderProduct.getId());
                QueryWrapper<ProOutsourcingOrderProductDetail> queryWrapperDetail = new QueryWrapper<>();
                queryWrapperDetail.eq("outsourcing_id", proOutsourcingOrderProduct.getId());
                queryWrapperDetail.eq("is_deleted", 0);
                queryWrapperDetail.orderByDesc("create_time");
                List<ProOutsourcingOrderProductDetail> details = this.proOutsourcingOrderProductDetailService.list(queryWrapperDetail);
                if (CollectionUtil.isNotEmpty(details)) {
                    //设置材料
                    proOutsourcingOrderProduct.setProductDetails(details);
                }
            }
            //设置产品列表
            searchVO.setProductList(list);
        }
        if (CollectionUtil.isNotEmpty(ids)) {
            List<ProOutsourcingOrderProductDetailGroupVo> details = this.proOutsourcingOrderProductDetailService.getProductDetailInfoBy(ids);
            if (CollectionUtil.isNotEmpty(details)) {
                searchVO.setGroupDetailList(details);
            }
        }
        return searchVO;
    }

    /**
     * 修改
     *
     * @param proOutsourcingOrderAddOrUpdateForm 修改的入参
     * @return 是否修改完成
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBy(ProOutsourcingOrderAddOrUpdateForm proOutsourcingOrderAddOrUpdateForm) {
        //1.修改订单的信息
        ProOutsourcingOrder byId = getById(proOutsourcingOrderAddOrUpdateForm.getId());
        BeanUtil.copyProperties(proOutsourcingOrderAddOrUpdateForm, byId);
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean updateById = this.updateById(byId);
        if (updateById) {
            //1. 删除原来的产品 重新插入
            QueryWrapper<ProOutsourcingOrderProduct> productQueryWrapper = new QueryWrapper<>();
            productQueryWrapper.eq("order_id", proOutsourcingOrderAddOrUpdateForm.getId());
            boolean remove = this.proOutsourcingOrderProductService.remove(productQueryWrapper);
            //删除成功
            if (remove) {
                List<ProOutsourcingOrderProduct> productList = proOutsourcingOrderAddOrUpdateForm.getProductList();
                //插入修改
                if (CollectionUtil.isNotEmpty(productList)) {
                    for (ProOutsourcingOrderProduct product : productList) {
                        product.setOrderId(proOutsourcingOrderAddOrUpdateForm.getId());
                        product.setUpdateTime(LocalDateTime.now());
                        product.setModifier(JwtUtils.getLoginUserId());
                        product.setModifierName(JwtUtils.getLoginUsername());
                        boolean save = this.proOutsourcingOrderProductService.save(product);
                        if (save) {
                            //删除产品物料
                            QueryWrapper<ProOutsourcingOrderProductDetail> queryWrapperDetail = new QueryWrapper<>();
                            queryWrapperDetail.eq("outsourcing_id", product.getId());
                            boolean info = this.proOutsourcingOrderProductDetailService.remove(queryWrapperDetail);
                            List<ProOutsourcingOrderProductDetail> productDetails = product.getProductDetails();
                            if (info) {
                                if (CollectionUtil.isNotEmpty(productDetails)) {
                                    for (ProOutsourcingOrderProductDetail productDetail : product.getProductDetails()) {
                                        productDetail.setOutsourcingId(product.getId());
                                        productDetail.setUpdateTime(LocalDateTime.now());
                                        productDetail.setModifier(JwtUtils.getLoginUserId());
                                        productDetail.setModifierName(JwtUtils.getLoginUsername());
                                    }
                                    this.proOutsourcingOrderProductDetailService.saveBatch(productDetails);
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 提交或者审核订单
     *
     * @param orderId 订单id
     * @param status  状态
     * @return 是否操作成功
     */
    @Override
    public Boolean audit(Long orderId, String status) {

        //1. 待提交 2.待审核 3.待签收 4. 完成
        ProOutsourcingOrder byId = getById(orderId);
        if (ObjectUtil.isNotEmpty(byId)) {
            Long departmentId = byId.getDepartmentId();
            //查询部门下的人
            List<User> byDepartmentId = userClient.getByDepartmentId(departmentId);
            if (CollectionUtil.isNotEmpty(byDepartmentId)) {
                List<Long> collect = byDepartmentId.stream().map(User::getId).collect(Collectors.toList());
                if (!collect.contains(JwtUtils.getLoginUserId())
                        && !"admin|admin".equals(JwtUtils.getLoginUsername())) {
                    return false;
                }
            }
            if ("1".equals(status)) {
                byId.setStatus("3");
                byId.setUpdateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                boolean updateById = this.updateById(byId);
                if (updateById) {
                    return true;
                }
            }else{
                byId.setStatus("1");
                byId.setUpdateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                boolean updateById = this.updateById(byId);
                if (updateById) {
                    return true;
                }
            }
        }
        return true;
    }

    /**
     * 提交委外订单
     *
     * @param orderId 订单id
     * @return 是否操作成功
     */
    @Override
    public Boolean submit(Long orderId) {
        ProOutsourcingOrder byId = getById(orderId);
        byId.setStatus("2");
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        return this.updateById(byId);
    }
}
